import Router from '@koa/router';
import logger from '../logger.js';
import response from '../response.js';
import { GetOpenID,getPhoneNumber } from '../common/wx.js';
import lsyPay from '../common/lsyPay.js';
import db from '../mysqlHelper.js';
import moment from 'moment';

const router = new Router();
router.prefix('/ad/api');

router.post(`/applet/getOpenID`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 code');
        return;
    }
    let res = await GetOpenID(body.code);
    if (res.code == 1) {
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success(res.data, '获取OpenID成功');
});
router.post(`/applet/getPhoneNumber`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 code');
        return;
    }
    let res = await getPhoneNumber(body.code);
    if (res.code == 1) {
        ctx.body = response.fail(res.msg);
        return;
    }
    if(typeof(res.data)=="string"){
        res.data=JSON.parse(res.data);
    }
    ctx.body = response.success(res.data, '获取手机号成功');
});

router.post(`/applet/createOrder`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.openid == null) {
        ctx.body = response.fail('缺少必填字段 openid');
        return;
    }
    if (body.order_id == null) {
        ctx.body = response.fail('缺少必填字段 order_id');
        return;
    }
    if (body.order_body == null) {
        body.order_body = '广告牌安全检测费';
    }
    //检查订单是否存在
    let order=await db.findOne('order_info',{id:body.order_id});
    if(order==null){
        ctx.body = response.fail('订单号错误，请使用正确的订单号');
        return;
    }
    if(order.pay_status==1){
        ctx.body = response.fail('订单已支付，请勿重复支付');
        return;
    }
    let pay_sn=moment().format('YYYYMMDDHHmmssSSS')+Math.floor(Math.random() * 1000000);
    console.log('正在创建支付订单', pay_sn,JSON.stringify(body));
    let res = await lsyPay.applet_pay(pay_sn, order.price*100,body.openid, body.order_body);
    if (res.errMsg)
    {
       ctx.body = response.fail('创建支付订单出错:'+ res.errMsg);
       return;
    }
    if (res.return_code != 'SUCCESS') {
        ctx.body = response.fail(res.return_msg);
        return;
    }
    await db.update('order_info',{pay_sn:pay_sn,pay_status:0},{id:body.order_id});
    ctx.body = response.success(res, '创建订单成功');
});



router.all(`/lsy/notify`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    console.info('接收到乐收赢支付回调', JSON.stringify(body));
    if(body.result_code=='PAY_SUCCESS'){
        //支付成功
        let order=await db.findOne('order_info',{pay_sn:body.pay_trace_no});
        if(order==null){
            console.error('订单号错误，请使用正确的订单号', JSON.stringify(body));
            ctx.body={return_code:"SUCCESS",return_msg:"订单号错误，请使用正确的订单号"};
            return;
        }
        order.pay_status=1;
        order.pay_time=  moment(body.pay_time,'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss');
        let res = await db.update('order_info',order,{id:order.id});
        if(res instanceof Error){
            console.error('更新订单状态失败',res.message, JSON.stringify(order));
            ctx.body={return_code:"Fail",return_msg:"更新订单状态失败"};
            return;
        }
        console.info('更新订单状态成功', JSON.stringify(order));
        ctx.body={return_code:"SUCCESS",return_msg:"成功"};
    }
    else{
        //支付失败
        console.error('接收到异常的支付回调', JSON.stringify(body));
        ctx.body={return_code:"SUCCESS",return_msg:"成功"};
    }
});

export { router };
